import AsyncStorage from '@react-native-community/async-storage';
import Trending from 'GitHubTrending';

// GitHubTrending Token
const AUTH_TOKEN = 'fd82d1e882462e23b8e88aa82198f166';

// 分辨是哪个模块的标识
export const FLAG_STORE = { flag_popular: 'popular', flag_trending: 'trending' };

export default class DataStore {

    // 保存数据
    saveData(url, data, callback) {
        if (!data || !url) return;
        AsyncStorage.setItem(url, JSON.stringify(this._wrapData(data)), callback);
    }

    // 获取数据
    _wrapData(data) {
        return { data: data, timestamp: new Date().getTime() }
    }

    // 获取本地数据
    fetchLocalData(url) {
        return new Promise((resolve, reject) => {
            AsyncStorage.getItem(url, (error, result) => {
                if (!error) {
                    try {
                        resolve(JSON.parse(result));
                    } catch (e) {
                        reject(e);
                        console.error(e);
                    }
                } else {
                    reject(error);
                    console.error(error);
                }
            })
        })
    }

    // 获取网络数据
    fetchNetData(url, flag) {
        return new Promise((resolve, reject) => {
            if (flag !== FLAG_STORE.flag_trending) {
                fetch(url)
                    .then((response) => {
                        if (response.ok) {
                            return response.json();
                        }
                        throw new Error('Network response was not ok');
                    })
                    .then((responseData) => {
                        this.saveData(url, responseData);
                        resolve(responseData);
                    })
                    .catch((error) => {
                        reject(error);
                    })
            }
            else {
                new Trending(AUTH_TOKEN).fetchTrending(url).then(items => {
                    if (!items) {
                        throw new Error('responseData is null');
                    }
                    this.saveData(url, items);
                    resolve(items);
                })
                    .catch(error => {
                        reject(error);
                    })
            }
        })
    }

    // 对比时间戳
    static checkTimestampValid(timestamp) {
        const currentData = new Date();
        const targetDate = new Date();
        targetDate.setTime(timestamp);
        if (currentData.getMonth() !== targetDate.getMonth()) return false;
        if (currentData.getDate() !== targetDate.getDate()) return false;
        if (currentData.getHours() !== targetDate.getHours() > 4) return false; // 有效期4个小时
        return true;
    }

    // 优先从本地获取数据，如果数据过时或不存在则从服务器获取数据，我们需要这样设计我们的代码
    fetchData(url, flag) {
        return new Promise((resolve, reject) => {
            this.fetchLocalData(url).then((wrapData) => {
                if (wrapData && DataStore.checkTimestampValid(wrapData.timestamp)) {
                    resolve(wrapData);
                } else {
                    this.fetchNetData(url, flag).then((data) => {
                        resolve(this._wrapData(data));
                    }).catch((error) => {
                        reject(error);
                    })
                }
            }).catch((error) => {
                this.fetchNetData(url, flag).then((data) => {
                    resolve(this._wrapData(data));
                }).catch((error) => {
                    reject(error);
                })
            })
        })
    }
}